﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using IniFile;
namespace WeighSystem.Class
{
    public class FileLog
    {
        public static Mutex mutexLog = new Mutex();

        private static string _logFileName = null;

        public enum LOGLEVEL
        {
            关闭 = 0,
            错误 = 1,
            警告 = 2,
            调试 = 3,
            信息 = 4,
        }

        private static LOGLEVEL _LogLevel = LOGLEVEL.信息;
        public static LOGLEVEL LogLevel
        {
            get { return _LogLevel; }
            set { _LogLevel = value; }
        }

        public static string LogFileName
        {
            get { return _logFileName; }
            set { _logFileName = value; }
        }

        public struct stLOGLEVEL
        {
            public LOGLEVEL lgLevel;
            public string LogText;
        }

        public static List<stLOGLEVEL> LogList = new List<stLOGLEVEL>();

        public static void WriteLogToFile(LOGLEVEL LgLevel, string LogText)
        {
            lock (LogList)
            {
                var lg = new stLOGLEVEL();
                lg.lgLevel = LgLevel;
                lg.LogText = LogText;
                LogList.Add(lg);
            }
        }

        static void LogOutThread()
        {
            while (true)
            {
                try
                {
                    foreach (var lg in LogList)
                    {
                        WriteLogToFileEx(lg.lgLevel, lg.LogText);
                        LogList.Remove(lg);
                    }
                }
                catch (Exception)
                {
                    ;
                }
                Thread.Sleep(200);
            }
        }

        public static void StartLog()
        {
            var spLotThread = new Thread(new ThreadStart(LogOutThread));
            spLotThread.IsBackground = true;
            spLotThread.Name = "LogOutThread";
            spLotThread.Priority = ThreadPriority.Normal;
            spLotThread.Start();
            return;
        }

        private static void WriteLogToFileEx(LOGLEVEL LgLevel, string LogText)
        {
            if (LgLevel > _LogLevel) return;
            string str = "";
            mutexLog.WaitOne();
            try
            {
                string FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\LogFiles";
                if (!Directory.Exists(FilePath))
                    Directory.CreateDirectory(FilePath);
                _logFileName = string.Format(@"{0}\Logs-{1}.txt", FilePath, DateTime.Now.ToString("yyyy-MM-dd"));
                var sw = new StreamWriter(_logFileName, true);
                str = string.Format("[{0}][{1}] {2}", LgLevel.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), LogText);

                sw.WriteLine(str);
                sw.Close();
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
            mutexLog.ReleaseMutex();
            Console.WriteLine(str);
        }

        public static void WriteLogToFile(LOGLEVEL LgLevel, byte[] LogText, int length)
        {
            if (LgLevel > _LogLevel) return;

            string str = "";

            mutexLog.WaitOne();

            try
            {
                var FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\LogFiles";
                if (!Directory.Exists(FilePath))
                    Directory.CreateDirectory(FilePath);
                _logFileName = string.Format(@"{0}\Logs-{1}.txt", FilePath, DateTime.Now.ToString("yyyy-MM-dd"));
                var sw = new StreamWriter(_logFileName, true);
                var output = "";
                for (int k = 0; k < length; k++)
                {
                    output += LogText[k].ToString("X2") + " ";
                }

                str = string.Format("[{0}][{1}] {2}", LgLevel.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), output);

                sw.WriteLine(str);
                sw.Close();
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
            mutexLog.ReleaseMutex();
            Console.WriteLine(str);
        }

        /// <summary>
        /// 写命令日志
        /// </summary>
        /// <param name="PortName">串口号</param>
        /// <param name="CmdText">命令字串</param>
        /// <param name="State">状态</param>
        public static void WriteCmdLog(string PortName, string CmdText, int Direction, int State, int curTimeSlice)
        {
            //string sql = string.Format("insert into CommandLog(PortName,CommandText,TimeSlice,Direction,State) values('{0}','{1}',{2},{3},{4})", PortName, CmdText, curTimeSlice.ToString(), Direction.ToString(), State.ToString());

           //CALL sql handle
        }


    }
}
